import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login'
import Home from '../views/Home/Index.vue'
import Buy from '../views/Buy'
import OrderConfirm from '../views/OrderConfirm'
import SubmitSuccess from '../views/SubmitSuccess'
import Personal from '../views/Personal'
import Order from '../views/Order'
import All from '@/views/Order/All'
import Completed from '@/views/Order/Completed'
import Obligation from '@/views/Order/Obligation'
import Pending from '@/views/Order/Pending'
import Refund from '@/views/Order/Refund'
import OrderDetail from '../views/OrderDetail'
import WorkBench from '../views/WorkBench'
import LeaveList from '../views/LeaveList'
import LeaveDetail from '../views/LeaveDetail'
import LeaveRequest from '../views/LeaveRequest'
import Sale from '../views/Sale'
import TimeCard from '../views/TimeCard'
import FirstLogin from '../views/FirstLogin'
import StuInfo from '@/views/StuInfo'
import BindStuds from '../views/BindStuds'
import EditStuInfo from '../views/EditStuInfo'
import StuDetails from '@/views/StuDetails'
import PaymentCode from '@/views/PaymentCode'
import CampusSwitch from '@/views/CampusSwitch'
import TeacherLeave from '@/views/TeacherLeave'

import { IsFirstLogin } from '@/api/user'
import { Toast, Dialog } from 'vant'

Vue.use(VueRouter)

const routes = [
  // {
  //   path: '/',
  //   redirect: '/home'
  // },
  {
    path: '/login',
    name: 'Login',
    component: Login
  }, {
    path: '/home',
    name: 'Home',
    component: Home
  }, {
    path: '/buy',
    name: 'Buy',
    component: Buy
  }, {
    path: '/orderConfirm',
    name: 'OrderConfirm',
    component: OrderConfirm
  }, {
    path: '/success',
    name: 'Success',
    component: SubmitSuccess
  }, {
    path: '/personal',
    name: 'Personal',
    component: Personal
  }, {
    path: '/order',
    name: 'Order',
    component: Order,
    children: [{
      name: 'order_All',
      path: '/order/all',
      component: All
    }, {
      name: 'order_Completed',
      path: '/order/completed',
      component: Completed
    }, {
      name: 'order_Obligation',
      path: '/order/obligation',
      component: Obligation
    }, {
      name: 'order_Pending',
      path: '/order/pending',
      component: Pending
    }, {
      name: 'order_Refund',
      path: '/order/refund',
      component: Refund
    }]
  }, {
    path: '/orderDetail',
    name: 'OrderDetail',
    component: OrderDetail
  }, {
    path: '/workBench',
    name: 'WorkBench',
    component: WorkBench
  }, {
    path: '/leaveList',
    name: 'LeaveList',
    component: LeaveList
  }, {
    path: '/leaveDetail',
    name: 'LeaveDetail',
    component: LeaveDetail
  }, {
    path: '/leaveRequest',
    name: 'LeaveRequest',
    component: LeaveRequest
  }, {
    path: '/sale',
    name: 'Sale',
    component: Sale
  }, {
    path: '/timeCard',
    name: 'TimeCard',
    component: TimeCard
  }, {
    path: '/firstLogin',
    name: 'FirstLogin',
    component: FirstLogin
  }, {
    path: '/stuInfo',
    name: 'StuInfo',
    component: StuInfo
  }, {
    path: '/bindStuds',
    name: 'BindStuds',
    component: BindStuds
  }, {
    path: '/editStuInfo',
    name: 'EditStuInfo',
    component: EditStuInfo
  }, {
    path: '/stuDetails',
    name: 'StuDetails',
    component: StuDetails
  }, {
    path: '/paymentCode',
    name: 'PaymentCode',
    component: PaymentCode
  }, {
    path: '/campusSwitch',
    name: 'CampusSwitch',
    component: CampusSwitch
  }, {
    path: '/teacherLeave',
    name: 'TeacherLeave',
    component: TeacherLeave
  },
  //  {
  // path: '/about',
  // name: 'About',
  // route level code-splitting
  // this generates a separate chunk (about.[hash].js) for this route
  // which is lazy-loaded when the route is visited.
  // component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  // }
]

const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach(async (to, from, next) => {
  let store = router.app.$store  
  if (to.path == '/' || store.getters.phone == '') {
    const params = new URLSearchParams(window.location.search.substring(1)); //查询url
    const code = params.get("code"); //获取url中的code
    // 是否重定向进入
    if (code) {
      console.log('重定向进入');
      // 重定向进入
      const result = await IsFirstLogin({
        code: code
      });
      if (result.result == 'OK' && result.data.isFirst == 'false') {
        const { data: { openid, roleType, phone, isBind } } = result
        console.log('用户非首次登录');
        store.commit('setOpenId', openid);
        store.commit('setRoleType', roleType);
        store.commit('setPhone', phone);
        store.commit('setIsBind', isBind);
        if (roleType == 'teacher') {
          store.commit('setCampusList', result.data.campusList)
          if (result.data.campusList.length > 1) {
            // 职工有多个校区
            next({
              path: '/firstLogin'
            })
          } else {
            // 职工只有一个校区
            store.commit('setCampusID', result.data.campusList[0].campusID)
            store.commit("setTeacherName", result.data.campusList[0].userName);
            next({
              path: '/workBench'
            })
          }
        }
        else if (roleType == 'parent' && isBind == 'true') {
          next({
            path: '/home'
          })
        }
        else if (roleType == 'parent' && isBind == 'false') {
          next({
            path: '/firstLogin'
          })
        }
      } else if (result.result == 'OK' && result.data.isFirst == 'true') {
        const { data: { openid, isBind } } = result
        console.log('用户首次登录');
        //首次登录
        store.commit('setOpenId', openid);
        store.commit('setIsBind', isBind);
        next({
          path: '/login'
        })
      }else if (result.result == 'Fail'&&result.code == 10001){
        // code已被使用
        window.location.href =
        "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx0740ff21ea7bee50&redirect_uri=http%3a%2f%2fyuncanteen3.51canteen.com%2fwx-elite%2feducation%2f&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect ";

      } else {
        // 请求失败
        console.log('请求失败,重新获取');
        Dialog.alert({
          title: '错误',
          message: '请求失败,是否重新加载页面？'
        }).then(() => {
          // on confirm
          // 重定向获取code
          window.location.href =
            "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx0740ff21ea7bee50&redirect_uri=http%3a%2f%2fyuncanteen3.51canteen.com%2fwx-elite%2feducation%2f&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect ";
        }).catch(() => {
          // on cancel

        });
      }
    } else {
      //非重定向进入 获取code
      console.log('非重定向进入获取code');
      window.location.href =
        "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx0740ff21ea7bee50&redirect_uri=http%3a%2f%2fyuncanteen3.51canteen.com%2fwx-elite%2feducation%2f&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect ";

      /**职工调试**/
      // store.commit('setRoleType', 'teacher')
      // store.commit('setCampusList', [
      //   {
      //     "campusID": "85b94b57-fec0-4d09-9950-b933b8b5e8ab",
      //     "campusName": "精英幼儿"
      //   },
      //   {
      //     "campusID": "7eef4abc-630c-44eb-8625-eed4c2dc03cc",
      //     "campusName": "江门市"
      //   }
      // ])
      // store.commit('setCampusID', '7eef4abc-630c-44eb-8625-eed4c2dc03cc')
      // store.commit('setPhone', '13556666666')
      // store.commit('setPhone', '13555555554')
      // next('/workBench')
      /**家长调试**/
      // store.commit('setRoleType', 'parent')
      // store.commit('setPhone', '15521323081')
      // store.commit('setPhone', '13686948977')
      // store.commit('setPhone', '18202062046')
      // next('/home')
    }
  } else {
    if (store.getters.getPhone == '' && store.getters.getOpenId == '') {
      // 无用户信息时重定向返回获取
      window.location.href =
        "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx0740ff21ea7bee50&redirect_uri=http%3a%2f%2fyuncanteen3.51canteen.com%2fwx-elite%2feducation%2f&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect ";
      
      /*家长调试*/
      // store.commit('setRoleType', 'parent')
      // store.commit('setPhone', '15521323081')
      // store.commit('setPhone', '13686948977')
      // store.commit('setPhone', '18202062046')
      // next('/home')

      /*职工调试*/
      // store.commit('setRoleType', 'teacher')
      // store.commit('setPhone', '13556666666')
      // store.commit('setPhone', '13555555554')
      // store.commit('setPhone', '15875030720')
      // next('/workBench')
    } else {
      // 普通页面跳转
      next(true)
    }
  }
})

export default router
